package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.pojo.Driver;
import com.ruoyi.service.DriverService;
import com.ruoyi.until.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: liufei
 * @Desc:
 * @create: 2024-11-07 09:29
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private DriverService driverService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 四位数字验证码
     * @param driver
     * @return
     */
    @PostMapping("/sendCode")
    public R sendCode(@RequestBody Driver driver){

        int code = RandomUtils.nextInt(1000, 9999);

        System.out.println("验证码："+code);

        LambdaQueryWrapper<Driver> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Driver::getUsername, driver.getUsername());

        Driver driver1 = driverService.getOne(wrapper);

        if (ObjectUtils.isEmpty(driver1)){
            return R.error("用户名不存在");
        }

        stringRedisTemplate.opsForValue().set("code:" + driver.getUsername(), String.valueOf(code), 1, TimeUnit.MINUTES);

        return R.ok(code);
    }


    @PostMapping("/login")
    public R login(@RequestBody Driver driver){

        LambdaQueryWrapper<Driver> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Driver::getUsername, driver.getUsername());

        Driver driver1 = driverService.getOne(wrapper);

        if (ObjectUtils.isEmpty(driver1)){
            return R.error("用户名不存在");
        }

        String code = stringRedisTemplate.opsForValue().get("code:" + driver.getUsername());

        if(StringUtils.isEmpty(code)){
            return R.error("验证码过期");
        }

        if (!code.equals(driver.getCode())){
            return R.error("验证码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("role", driver1.getRole()).claim("userId", driver1.getId()).compact();

        stringRedisTemplate.opsForValue().set("token:" + driver1.getId(), token, 5, TimeUnit.MINUTES);

        return R.ok(token);
    }


}
